package cn.com.cetccst.compliancecheck.demo.dialog;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import java.util.ArrayList;
import java.util.List;

import cn.com.cetccst.compliancecheck.demo.R;

public class AppListDlg extends AlertDialog.Builder {
    private ArrayList<String> packageNameList = new ArrayList<>();
    private boolean[] checkResult;

    public static void show(Context context, List<String> curSelectedApps, Callback callback) {

        new AppListDlg(context, curSelectedApps, callback).show().setCanceledOnTouchOutside(false);
    }

    public AppListDlg(@NonNull Context context, List<String> curSelectedApps, Callback callback) {
        super(context);
        getAppList(context);
        checkResult = new boolean[packageNameList.size()];
        for (int i = 0; i < checkResult.length; i++) {
            checkResult[i] = curSelectedApps.contains(packageNameList.get(i));
        }

        AppListAdapter adapter = new AppListAdapter(context);
        ListView listView = new ListView(context);
        listView.setAdapter(adapter);
        setView(listView)
                .setPositiveButton("确定", (dialog, which) -> {
                    handleOK(callback);
                })
                .setNegativeButton("取消", null)
                .setCancelable(false);
    }

    private void handleOK(Callback callback) {
        List<String> ret = new ArrayList<>();
        for (int i = 0; i < checkResult.length; i++) {
            if (checkResult[i]) {
                ret.add(packageNameList.get(i));
            }
        }
        callback.handleSelected(ret);
    }

    public interface Callback {
        void handleSelected(List<String> selectedAppList);
    }

    private void getAppList(Context context) {
        String self = context.getPackageName();
        packageNameList.clear();
        final PackageManager packageManager = context.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        final List<ResolveInfo> rinfo = packageManager.queryIntentActivities(mainIntent, 0);
        for (ResolveInfo app : rinfo) {
            if ((app.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
                    && !app.activityInfo.packageName.equals(self)) {// 第三方应用
                packageNameList.add(app.activityInfo.packageName);
            }
        }
    }

    private class AppListAdapter extends ArrayAdapter<String> {
        private final Context context;

        public AppListAdapter(Context context) {
            super(context, R.layout.checkbox_item, packageNameList);
            this.context = context;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.app_info_item, parent, false);
            }
            try {
                String item = getItem(position);
                PackageManager packageManager = context.getApplicationContext().getPackageManager();
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(item, PackageManager.GET_UNINSTALLED_PACKAGES);
                Drawable drawable = applicationInfo.loadUnbadgedIcon(packageManager);
                ImageView appIcon = convertView.findViewById(R.id.appIcon);
                appIcon.setImageDrawable(drawable);

                String label = packageManager.getApplicationLabel(applicationInfo).toString();
                setTextViewText(convertView, R.id.appName, label);
                setTextViewText(convertView, R.id.pkgName, item);

                CheckBox checkBox = convertView.findViewById(R.id.checkBox);
                checkBox.setOnCheckedChangeListener(null);
                checkBox.setChecked(checkResult[position]);
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                        checkResult[position] = checked;
                    }
                });
            } catch (PackageManager.NameNotFoundException e) {

            }
            return convertView;
        }

        private void setTextViewText(View item, int resId, String text) {
            TextView textView = item.findViewById(resId);
            textView.setText(text);
        }
    }
}
